//
//  XBHomeController.swift
//  Sina
//
//  Created by 周旭斌 on 2017/3/23.
//  Copyright © 2017年 周旭斌. All rights reserved.
//

import UIKit
import SVProgressHUD

class XBHomeController: XBBaseTableViewController {
    
    var dataArray = [XBHomeModel]();

    override func viewDidLoad() {        
        super.viewDidLoad()
        
        title = "首页";
        
        // 这是tableView
        setUpTableView();
        
        // 请求页面数据
        SVProgressHUD.show(withStatus: "正在加载...");
        XBNetWorkTool.shareInstance().get("http://dx.sitemn.com/ser/familys.ashx?action=getNewsList&aid=52&page=1&uid=122", parameters: nil, progress: { (progress) in
            }, success: { (dataTask, responseData) in
                
                // 一般不会走这里
                guard let data = responseData as? [String : AnyObject] else {
                    print("没有数据");
                    SVProgressHUD.showError(withStatus: "服务器出错!");
                    return;
                }
                
                if let status = data["status"] {
                    if (("\(status)" as NSString).isEqual(to: "0")) {
                        SVProgressHUD.dismiss();
                        self.dataArray = XBHomeModel.dcObjectArrayWithKeyValuesArray(data["data"] as! NSArray) as! [XBHomeModel];
                        self.tableView.reloadData();
                    }else {
                        SVProgressHUD.showInfo(withStatus: data["message"] as! String);
                    }
                }
                
                
                print(data);
                
        }) { (responseData, Error) in
            SVProgressHUD.show(withStatus: "网络繁忙,请稍后再试!");
        }
    }
    
    // MARK:设置UI
    private func setUpTableView() {
        tableView.rowHeight = UITableViewAutomaticDimension;
        tableView.estimatedRowHeight = 56;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

// MARK:tableViewDataSource
extension XBHomeController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count;
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = XBHomeCell.homeCellWith(tableView);
        let model = dataArray[indexPath.row];
        cell.model = model;
        return cell;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true);
        navigationController?.pushViewController(XBtestController(), animated: true);
    }
}
